import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormArray, Validators} from '@angular/forms';

@Component({
  selector: 'app-myform',
  templateUrl: './myform.component.html',
  styleUrls: ['./myform.component.css']
})


export class MyformComponent implements OnInit {
  // formarray表单
  groupForm = this.fb.group({
    Arr: this.fb.array([this.createForm({})]) // formarray
  });
  private createForm(data) {
    const control1 = data.control1 || '';
    const control2 = data.control2 || '';
    const Name = data.Name || '';
    const Code = data.Code || '';
    const Level = data.Level || '';
    const Remark = data.Remark || '';
    return  this.fb.group({
      control1:  [control1],
      control2:  [control2],
      Name:  [Name],
      Code:  [Code],
      Level:  [Level],
      Remark:  [Remark],
    });
  };

  // 增加表单
  newForm() {
    const arr = this.groupForm.get('Arr') as FormArray;
    arr.push(this.createForm({})); // 推送form新表单
  }

  // 移除表单
  removeForm(i: number) {
    const arr = this.groupForm.get('Arr') as FormArray;
    arr.removeAt(i); // 根据索引移除对应的表单
  }

  onSubmit() {
    // TODO: Use EventEmitter with form value
    console.warn(this.groupForm.value);
  }

  get ArrForm() {
    return this.groupForm.get('Arr') as FormArray;
  }


  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    const arr = this.groupForm.get('Arr') as FormArray;
    console.log(arr)
    var data = { "control1": "123", "control2": "23", "Name": "324", "Code": "342", "Level": "32432", "Remark": "324423" };
    arr.push(this.createForm(data));

  }

}
